package me.yuxiaoyao.lock.zookeeper;

import me.yuxiaoyao.lock.LockExecutor;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.integration.zookeeper.config.CuratorFrameworkFactoryBean;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;

/**
 * @author kerryzhang on 2021/01/05
 */

@Import(IntegrationZookeeperProperties.class)
@ConditionalOnClass(CuratorFramework.class)
public class ZookeeperLockRegistryConfiguration {
    private final IntegrationZookeeperProperties properties;

    public ZookeeperLockRegistryConfiguration(IntegrationZookeeperProperties properties) {
        this.properties = properties;
    }


    @Bean
    @ConditionalOnMissingBean
    public CuratorFrameworkFactoryBean curatorFrameworkFactoryBean(@Autowired(required = false) RetryPolicy retryPolicy) {
        if (retryPolicy == null) {
            return new CuratorFrameworkFactoryBean(properties.getUrl());
        } else {
            return new CuratorFrameworkFactoryBean(properties.getUrl(), retryPolicy);
        }
    }


    @Bean
    @ConditionalOnMissingBean
    public ZookeeperLockRegistry redisLockRegistry(CuratorFramework client) {
        return new ZookeeperLockRegistry(client, properties.getRegistryKey());
    }

    @Bean
    @ConditionalOnMissingBean
    public LockExecutor lockExecutor(ZookeeperLockRegistry zookeeperLockRegistry) {
        return new ZookeeperLockExecutor(zookeeperLockRegistry);
    }

}
